package win.devhu.testing.javalinweb

import com.google.gson.GsonBuilder
import io.javalin.Javalin
import io.javalin.apibuilder.ApiBuilder.get
import io.javalin.apibuilder.ApiBuilder.path
import io.javalin.json.FromJsonMapper
import io.javalin.json.JavalinJson
import io.javalin.json.ToJsonMapper
import io.javalin.rendering.template.TemplateUtil.model
import org.slf4j.LoggerFactory

class HelloJavalin

data class GsonTest(var status:Int,var msg:String)

private val log = LoggerFactory.getLogger(HelloJavalin::class.java)

fun main(args: Array<String>) {
    //For Gson
    val gson = GsonBuilder().create()
    JavalinJson.fromJsonMapper = object : FromJsonMapper {
        override fun <T> map(json: String, targetClass: Class<T>) = gson.fromJson(json, targetClass)
    }
    JavalinJson.toJsonMapper = object : ToJsonMapper {
        override fun map(obj: Any): String = gson.toJson(obj)
    }

    val port = Config.getPort() ?: 7000     //config custom port
    val app = Javalin.create().start(port)

    app.routes {
        get("/") {
            ctx -> ctx.render("/templates/index.ftl", model("message", "Hello Freemarker!")) }
        path("/api"){
            get("/gson"){ctx -> ctx.json(GsonTest(200,"it's OK"))}
        }
    }

}


